package com.lai.qq.admin.modules.basic.api;

import com.lai.qq.admin.config.Constants;
import com.lai.qq.admin.modules.common.api.BaseController;
import com.lai.qq.admin.modules.common.dto.output.ApiResult;
import com.lai.qq.admin.utils.Constant;
import com.lai.qq.admin.utils.JwtTokenUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 *  <p> 首页 </p>
 *
 */
@Slf4j
@RestController
@Api(description = "首页-接口")
public class IndexController extends BaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping(value = "/login", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "登录系统", httpMethod = "GET", response = ApiResult.class)
    public ApiResult login() {
        return ApiResult.ok("登录系统成功", null);
    }


    @GetMapping(value = "/logout", produces = "application/json;charset=utf-8")
    @ApiOperation(value = "注销系统", httpMethod = "GET", response = ApiResult.class)
    public ApiResult logout(HttpServletRequest request,HttpServletResponse response) {
        String token = request.getHeader(Constants.REQUEST_HEADER);
        log.info("/logout,获取请求头部的token={}", token);
        Map<String, Object> claims = jwtTokenUtil.getClaimsFromToken(token);
        if(claims==null){
            throw new BadCredentialsException("TOKEN已过期，请重新登录！");
        }
        String userId = jwtTokenUtil.getUserId(token);
        if (StringUtils.isNotBlank(token) && !"undefined".equals(token)) {
            // 检查token
            redisTemplate.delete(Constant.DILINK_ADMIN_ACCESS_TOKEN + userId);
        }
        return ApiResult.ok("注销系统成功", null);
    }
}
